//服务端程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>

int main()
{
	//创建socket
	int lfd = socket(AF_INET, SOCK_STREAM, 0);
	if(lfd < 0)
	{
		perror("error\n");
		return -1;
	}

	//绑定
	struct sockaddr_in serv;
	bzero(&serv, sizeof(serv));
	serv.sin_family = AF_INET;
	serv.sin_port = htons(8888);
	serv.sin_addr.s_addr = htonl(INADDR_ANY); //表示使用本机任意可用ip
	int ret = bind(lfd,(struct sockaddr *) &serv, sizeof(serv));
	if(ret < 0)
	{
		perror("error\n");
	}
	
	//监听
	listen(lfd, 128);
	
	struct sockaddr_in client;
	socklen_t len = sizeof(client);
	int cfd;
	while(1)
	{
		//接受客户端连接
		cfd = accept(lfd, (struct sockaddr *)&client, &len);
		
		//创建一个子进程，让子进程去处理数据
		pid_t pid = fork();
		if(pid < 0)
		{
			perror("fork error");
			exit(-1);
		}
		//父进程
		else if(pid > 0)
		{
			//关闭通信描述符
			close(cfd);
		}
		else if(pid == 0)
		{
			close(lfd);
			//获取client端的ip
			char sIP[16];
			memset(sIP, 0x00, sizeof(sIP));
			inet_ntop(AF_INET, &client.sin_addr.s_addr,sIP,sizeof(sIP));
			//printf("IP == [%s],PORT == [%d]", sIP, ntohs(client.sin_port));

			int n = 0;
			char buf[1024];
			while(1)
			{
				//读数据
				memset(buf, 0x00, sizeof(buf));
				n = read(cfd, buf, sizeof(buf));
				if(n <= 0)
				{
					printf("read error or connect close.\n");
					break;
				}
				printf("pid==[%d],IP==[%s],n==[%d],buf==%s\n",getpid(), sIP, n, buf);
				for(int i = 0; i < n; ++i)
				{
					buf[i] = toupper(buf[i]);
				}	
				//发数据
				write(cfd, buf, n);
			}

			close(cfd);
			//务必要有exit(-1);
			exit(-1);
		}
	}

	close(lfd);

	return 0;
}
